package main

import (
    "encoding/json"
    "net/http"
    "strings"
)

const (
    HttpApiErrCommon            = 10000
    HttpApiErrBadRequest        = 10001
    HttpApiErrDesktopIsFull     = 10002
    HttpApiErrDesktopIsOnline   = 10003
)

type HttpApiHandle struct {
}

type Response struct {
    Success string `json:"success"`
    ErrId   int `json:"err_id"`
    ErrMsg  string `json:"err_msg"`
}

func errorResponse(code int, success bool, errId int, msg string, w http.ResponseWriter) {
    ret := Response{}
    if success {
        ret.Success = "1"
    } else {
        ret.Success = "0"
    }
    ret.ErrId = errId
    ret.ErrMsg = msg
    buf, _ := json.Marshal(&ret)
    
    jsonResponse(code, buf, w)
}

func jsonResponse(code int, body []byte, w http.ResponseWriter) {
    w.Header().Set("Connection", "close")
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(code)
    w.Write(body)
}

func (h *HttpApiHandle) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    if strings.Index(req.URL.Path, "/client/new") == 0 {
        handleDesktopClientNew(w, req)
    } else if strings.Index(req.URL.Path, "/client/heartbeat") == 0 {
        handleDesktopClientHeartBeat(w, req)
    } else if strings.Index(req.URL.Path, "/client/disconnect") == 0 {
        handleDesktopClientDisconnect(w, req)
    } else if strings.Index(req.URL.Path, "/client/state") == 0 {
        handleDesktopClientState(w, req)
    } else if strings.Index(req.URL.Path, "/software/task/new") == 0 {
        handleSoftwareTaskNew(w, req)
    } else if strings.Index(req.URL.Path, "/software/task/state") == 0 {
        handleSoftwareTaskState(w, req)
    } else if strings.Index(req.URL.Path, "/software/task/delete") == 0 {
        handleSoftwareTaskDelete(w, req)
    } else if strings.Index(req.URL.Path, "/software/list/state") == 0 {
        handleSoftwareListState(w, req)
    } else if strings.Index(req.URL.Path, "/software/list/upload") == 0 {
        handleSoftwareListUpload(w, req)
    } else {
        errorResponse(403, false, HttpApiErrCommon, "forbidden path or method", w)
    }
}

func HttpApiServiceStart() {
    c := getConfig()

    s := &http.Server{
        Addr: c.HttpApi.ListenAddr,
        Handler: &HttpApiHandle{},
    }

    go func() {
        mainLog.Fatal(s.ListenAndServeTLS(c.HttpApi.CrtFile, c.HttpApi.KeyFile))
    }()
}
